package com.ygqh.baby.controller.mobile;

import com.fasterxml.jackson.databind.util.JSONPObject;
import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.mp.model.OauthToken;
import com.foxinmy.weixin4j.payment.PayRequest;
import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.po.YgOrder;
import com.ygqh.baby.po.YgPlatform;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.service.*;
import com.ygqh.baby.service.pay.UnifiedOrderResult;
import com.ygqh.baby.service.wechat.YgWeChatService;
import com.ygqh.baby.utils.SessionUtil;
import com.ygqh.baby.utils.WebUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;

/**
 * 壹家店登录
* @ClassName: YgPlatformLoginController 
* @author (guohao)  
* @date 2018年5月25日 上午11:34:59 
* @version V1.0
 */
@Controller
@RequestMapping("/platform/pay")
public class YgPlatformPayController {

	private Logger logger = Logger.getLogger(YgPlatformPayController.class);

	@Autowired
	private YgUserService ygUserService;
	@Autowired
	private YgOrderLogService ygOrderLogService;
	@Autowired
	private YgOrderService ygOrderService;
	@Autowired
	private YgFrameCodeService ygFrameCodeService;
	@Autowired
	private YgOrderPaymentService ygOrderPaymentService;
	@Autowired
	private WxSmallAuthorityService wxSmallAuthorityService;
	@Autowired
	private YgWeChatService weChatService;
	@Autowired
	private YgPayService ygPayService;

	@Autowired
	private YgPlatformService ygPlatformService;
	@Autowired
	private WxMpAuthorityService wxMpAuthorityService;
	@Autowired
	private YgUserAuthsService ygUserAuthsService;

	@RequestMapping(value = "orderPay")
	@ResponseBody
	public JSONPObject UnifiedOrderJSAPI(String platformNo, Long orderId, BigDecimal totalPrice, String callback, HttpServletRequest request)
			throws IOException {

		JSONPObject json = null;
		String ipAddress = WebUtils.getIpAddr(request);
		String[] split = ipAddress.split(",");
		ipAddress = split[0];
		YgUser user = SessionUtil.getCurrentUser();
		PayRequest payRequest = null;
		// 记录入参日志
		ygOrderLogService.addOrderLog(orderId, OrderStatus.WaitingPay, "small", "小程序支付：入参【orderId：" + orderId + ";totalPrice：" + totalPrice + "】");
		// 判断该订单是否已经支付过
		YgOrder ygOrder = ygOrderService.findByOrderId(orderId);
		if (ygOrder != null && !ygOrder.getOrderStatus().equals(OrderStatus.WaitingPay)) {
			return new JSONPObject(callback, Message.success(true));
		}
		try {

			// 生成支付流水
			Long paymentCode = ygFrameCodeService.getFrameCode(CodeType.OrderPM, new Date());

			int totalFee = totalPrice.multiply(new BigDecimal(100)).intValue();

			String notify_url = null;
			platformNo = "001";
			payRequest = wxSmallAuthorityService.createPrePayByProvider(platformNo, user.getSmallOpenId(), paymentCode, totalFee, ipAddress, notify_url, null);
			ygOrderPaymentService.addPaymentRecord(BusinessModule.Order, orderId.toString(), totalPrice, paymentCode.toString(), PayType.Small, AppType.Small,
					payRequest.getPrepayId(), platformNo, null);

		} catch (Exception e) {
			ygOrderLogService.addOrderLog(orderId, OrderStatus.WaitingPay, "small", "小程序;发起微信支付失败" + e.getMessage());
			e.printStackTrace();
			return new JSONPObject(callback, Message.error("", null));
		}
		json = new JSONPObject(callback, Message.success(payRequest));
		return json;
	}

	@RequestMapping(value = "orderPay1")
	@ResponseBody
	public JSONPObject unifiedOrder(String code, String platformNo, Long orderId, @RequestParam(defaultValue = "Small") AppType appType,
			@RequestParam(defaultValue = "WeChat") PayType payType, BigDecimal price, String callback, HttpServletRequest request) throws WeixinException {
		YgUser user = SessionUtil.getCurrentUser();
		String ipAddress = WebUtils.getIpAddr(request).split(",")[0];
		String openId = this.getOpenId(user.getId(), appType, platformNo, code);

		// String openId = "oYtnzwNiCCaIyc63_QjzoHuT7Zvs";
		// String openId = "o26750Fv0xMnvBSgFFXs7WgqzTbo";
		// String openId = "o4_TS5GWk6AeiRhCIFvAHZAVXau0";

		YgOrder ygOrder = ygOrderService.findByOrderId(orderId);
		if (ygOrder != null && !ygOrder.getOrderStatus().equals(OrderStatus.WaitingPay)) {
			//
		}
		Long paymentCode = ygFrameCodeService.getFrameCode(CodeType.OrderPM, new Date());
		YgPlatform platform = ygPlatformService.findByPlatformNo(platformNo);

		UnifiedOrderResult result = ygPayService.unifiedOrder(platform, AppType.Small, PayType.WeChat, paymentCode.toString(), price, ipAddress, openId, null, "");

		ygOrderPaymentService.addPaymentRecord(BusinessModule.Order, orderId.toString(), price, paymentCode.toString(), payType, appType, result.getPrepayId(),
				platformNo, result.getPlatformName());

		return new JSONPObject(callback, result);
	}

	private String getOpenId(Long userId, AppType appType, String platformNo, String code) throws WeixinException {
		if (AppType.Android.equals(appType) || AppType.Ios.equals(appType)) {
			return null;
		}

		YgUser ygUser = ygUserService.findOpenId(userId);
		String openId = null;
		if (AppType.WeChat.equals(appType)) {
			openId = ygUser.getOpenId();

			if (StringUtil.isBlank(openId)) {
				// 公众号支付openId 为空 需要授权获取
				if (StringUtils.isNotEmpty(code)) {
					OauthToken oauthToken = wxMpAuthorityService.findOauthToken(code);
					openId = oauthToken.getOpenId();
					ygUserService.bindingOpenId(userId, openId, null, oauthToken.getUnionId());
				}
			}
		} else if (AppType.Small.equals(appType)) {
			if (StringUtil.isNotBlank(platformNo)) {
				openId = ygUserAuthsService.getOpenId(userId, platformNo, AppType.Small);
			} else {
				openId = ygUser.getSmallOpenId();
			}
		}

		return openId;
	}

	@RequestMapping(value = "unifiedOrderCallBack")
	public void unifiedOrderCallBack(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		ServletInputStream in = request.getInputStream();
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = in.read(buffer)) != -1) {
			out.write(buffer, 0, len);
		}
		String result = new String(out.toByteArray(), "UTF-8");
		ygOrderLogService.addOrderLog(1l, OrderStatus.WaitingSend, "系统", "微信支付回调，回调数据 【" + result + "】;");

		String res = weChatService.UnifiedOrderCallBack(result);

		ygOrderLogService.addOrderLog(1l, OrderStatus.WaitingSend, "系统", "微信支付回调，返回微信数据 【" + res + "】;");
		logger.debug("\n微信支付回调返回结果：\n" + res);
		out.close();
		in.close();
		response.getWriter().print(res);
	}
}
